<template>
  <el-card class="container">
    <el-form :model="attr" :rules="rules" ref="form">
      <el-form-item label="属性名" prop="attrName" label-width="80px">
        <el-input
          v-model="attr.attrName"
          placeholder="请输入属性名"
          class="save-attr-input"
        />
      </el-form-item>

      <el-form-item prop="attrValueList">
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!attr.attrName"
          @click="addEmptyAttrValue"
        >
          添加属性值
        </el-button>

        <el-table :data="attr.attrValueList" border class="table">
          <el-table-column
            type="index"
            label="序号"
            width="50"
            align="center"
          />
          <el-table-column prop="attrName" label="属性值名称">
            <template v-slot="{ row, $index }">
              <!--
            编辑模式

            ref="input" 当出现多个input时，标识input后面会覆盖前面
            解决：给每一个input取一个唯一的标识
          -->
              <el-input
                placeholder="请输入属性值名称"
                size="mini"
                :ref="$index"
                v-show="row.isEdit"
                @blur="handleInputBlur(row, $index)"
                v-model="row.valueName"
              />
              <!-- 显示模式 -->
              <div v-show="!row.isEdit" @click="showEdit(row, $index)">
                {{ row.valueName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <!-- 当里面写了内容，prop就没有意义了（不会生效） -->
            <template v-slot="{ row, $index }">
              <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="取消"
                icon="el-icon-info"
                icon-color="red"
                :title="`确定要删除 ${row.valueName} 属性值吗？`"
                @onConfirm="attr.attrValueList.splice($index, 1)"
              >
                <el-tooltip
                  effect="dark"
                  content="删除属性值"
                  placement="top"
                  slot="reference"
                >
                  <el-button type="danger" icon="el-icon-delete" size="mini" />
                </el-tooltip>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>

    <el-button type="primary" @click="submitForm">确认</el-button>
    <el-button @click="$emit('setIsShowAttrList', true)">取消</el-button>
  </el-card>
</template>

<script>
import { mapState } from 'vuex'
import { reqSaveAttr } from '@/api/product/attr'

export default {
  name: 'SaveAttr',
  props: {
    currentAttr: {
      type: Object,
      default: () => ({
        // 属性名
        attrName: '',
        // 属性值列表
        attrValueList: []
      })
    }
  },
  data() {
    // 自定义校验规则
    const validator = (rule, value, callback) => {
      /*
        rule, 校验的规则项（包含表单项名称）
        value, 校验的表单项的值
        callback 注意: 必须要调用的函数
          callback() 校验通过
          callback(xxx) 校验失败，xxx就是失败的原因
      */
      if (value.length) {
        callback()
        return
      }

      callback('请至少添加一个属性值')
    }

    return {
      attr: this.currentAttr,
      rules: {
        attrName: [
          { required: true, message: '请输入属性名', trigger: 'blur' }
        ],
        attrValueList: [{ required: true, validator }]
      },
      isEdit: true,
      visible: false
    }
  },
  computed: {
    ...mapState('category', ['category3Id'])
  },
  methods: {
    // 添加空的属性值
    addEmptyAttrValue() {
      // 更新响应式数据
      // 内部dep->watcher，将watcher添加到异步队列中等待执行
      // 就是通过$nextTick添加的
      this.attr.attrValueList.push({
        // 决定显示哪种模式（编辑/显示）
        isEdit: true,
        // 属性值名称
        valueName: ''
      })
      /*
        $nextTick
          简单理解：等DOM元素更新好，再触发其中的回调
          真实理解：将其中的回调添加到异步队列中等待执行，队列先进先出
      */
      // 更新是异步的
      // 让input聚焦
      this.$nextTick(() => {
        this.$refs[this.attr.attrValueList.length - 1].focus()
      })
    },
    // 显示编辑模式
    showEdit(row, index) {
      // 更新属性时，数据一上来没有isEdit属性，他不是响应式数据
      // row.isEdit = true
      this.$set(row, 'isEdit', true)
      this.$nextTick(() => {
        this.$refs[index].focus()
      })
    },
    // 处理input失去焦点
    handleInputBlur(row, index) {
      if (!row.valueName) {
        this.attr.attrValueList.splice(index, 1)
        return
      }
      row.isEdit = false
    },
    // 确认
    submitForm() {
      // 验证属性名和属性值是否都有
      const { attrName, attrValueList } = this.attr
      const { category3Id } = this

      this.$refs.form.validate(async valid => {
        if (valid) {
          const { attrName, attrValueList, id } = this.attr
          await reqSaveAttr({
            attrName,
            attrValueList: attrValueList.map(attrValue => {
              return {
                valueName: attrValue.valueName
              }
            }),
            categoryId: category3Id,
            categoryLevel: 3,
            id
          })
          this.$message({
            type: 'success',
            message: `${id ? '修改' : '添加'}属性成功~`
          })
          this.$emit('setIsShowAttrList', true)
        }
      })
    }
  }
}
</script>

<style lang="sass" scoped>
.table
  margin: 20px 0
.save-attr-input
  width: 200px
</style>
